import java.io.*;
import  java.net.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Server3 {
    public static void main(String[] args) throws Exception{
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(5312);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("等待客户呼叫");
        try {
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String keylength = in.readUTF();
            byte []kb = new byte[Integer.parseInt(keylength)];
            System.out.println("收到的密钥为：");
            for(int i = 0;i<Integer.parseInt(keylength);i++) {
                String str = in.readUTF();
                kb[i] = Byte.parseByte(str);
                System.out.print(kb[i] + " ");
            }
            while(true) {
                SecretKeySpec k = new SecretKeySpec(kb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                String clength = in.readUTF();
                byte ctext[] = new byte[Integer.parseInt(clength)];
                for (int i = 0;i<Integer.parseInt(clength);i++) {
                    String temp = in.readUTF();
                    ctext[i] = Byte.parseByte(temp);
                }
                byte[] ptext = cp.doFinal(ctext);
                String question = new String(ptext,"UTF8");
                System.out.print("\n后缀表达式为："+ question);
                MyDC getanswer = new MyDC();
                getanswer.set(question);
                Rational answer = getanswer.get();
                int a = answer.getNumerator();
                int b = answer.getDenominator();
                float result = (float) a / b;
                System.out.println("\n计算出的结果为"+String.format("%.2f",result));
                out.writeUTF(String.format("%.2f",result));
                Thread.sleep(500);
            }
        } catch (IOException e) {
            System.out.println("客户已断开" + e);
        }
    }
}